%----------------------------------------------------------
% include script for trigger processing
% purpose: better readability in stim and feedback funcions
%----------------------------------------------------------

% check for trigger events
if bci.param.doReceiveTrigger && curEventNo>0 && trigRec(curEventNo)==0, % last trigger not received
    if isempty(bci.init.trigChan), % single event based (e.g. brainamp)
        trigData=zeros(1,newsamples+1);
        try
            evt = buffer('get_evt', [curEventNo-1 curEventNo-1], 'localhost', 1972);
            trigData(evt.sample-startSample-datCount+1) = str2double(char(evt.buf(2:end-1)));
        catch
        end
    else
        if length(bci.init.trigChan)>1,
            trigData = bciAnalog2Trig(MEMdata(bci.init.trigChan,max(datCount,1):datCount+newsamples),bci.param.trigChanOrder);
            % (count from datCount instead of datCount+1 to
            % detect trigger onset at window start)
        else
            trigData = MEMdata(bci.init.trigChan,max(datCount,1):datCount+newsamples);
        end
    end
    if bci.paradigm.id==12||bci.paradigm.id==14,
        % remove P300 paradigm synchronization trigger
        trigData(trigData>=bci.paradigm.flashSyncTrigger)=0;
    end
    trigIdx = find(diff(trigData)>0);
    if ~isempty(trigIdx),
        trigRecTime(curEventNo)=GetSecs-startTime;
        trigRec(curEventNo) = trigData(trigIdx(1)+1);
        trigPos(curEventNo) = datCount+trigIdx(1);
        lastEventSamp=trigPos(curEventNo);
        eventChanged=true;
        lastEvent=trigRec(curEventNo);
        if lastEvent>2^14, lastEvent=lastEvent-2^14; end % solves MEG trigger bug
        if abs(lastEventSamp/bci.srate-eventTime(curEventNo))>1,
            fprintf('Warning: trigger event timing difference > %2.2f s\n',...
                lastEventSamp/bci.srate-eventTime(curEventNo));
        end
        if curEvent~=lastEvent && any(bci.eventsToClassify==lastEvent),
            fprintf('Warning: trigger sent: %i @ %3.2f s received: % i @ %3.2f s.\n',...
                curEvent,eventTime(curEventNo),lastEvent,lastEventSamp/bci.srate);
            lastEvent = curEvent;
        end
    end
end
